package flutterdemo.service;

import flutterdemo.config.UploadConfig;
import flutterdemo.dao.FileDao;
import flutterdemo.model.File;
import flutterdemo.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

import static flutterdemo.utils.FileUtils.generateFileName;
import static flutterdemo.utils.UploadUtils.*;

/**
 * 文件上传服务
 */
@Service
public class FileService {
    @Autowired
    private FileDao fileDao;

    /**
     * 上传文件
     * 
     * @param md5
     * @param file
     */
    public String upload(
            String md5,
            MultipartFile file) throws IOException {
        @SuppressWarnings("null")
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = generateFileName() + fileSuffix;
        String imagesPath = UploadConfig.imagesPath + fileName;
        String webPath = UploadConfig.webPath + fileName;
        FileUtils.write(imagesPath, file.getInputStream());
        fileDao.save(new File(fileName, md5, webPath, new Date()));
        return webPath;
    }

    /**
     * 分块上传文件
     * 
     * @param md5
     * @param size
     * @param chunks
     * @param chunk
     * @param file
     * @throws IOException
     */
    public void uploadWithBlock(String name,
            String md5,
            Long size,
            Integer chunks,
            Integer chunk,
            MultipartFile file) throws IOException {
        String fileName = getFileName(md5, chunks);
        FileUtils.writeWithBlok(UploadConfig.imagesPath + fileName, size, file.getInputStream(), file.getSize(), chunks,
                chunk);
        addChunk(md5, chunk);
        if (isUploaded(md5)) {
            removeKey(md5);
            fileDao.save(new File(name, md5, UploadConfig.imagesPath + fileName, new Date()));
        }
    }

    /**
     * 检查Md5判断文件是否已上传
     * 
     * @param md5
     * @return
     */
    public boolean checkMd5(String md5) {
        File file = new File();
        file.setMd5(md5);
        return fileDao.getByFile(file) == null;
    }
}
